package com.yunmaozj.easydb.common;

import com.yunmaozj.easydb.annotions.EasyDB;

import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.security.CodeSigner;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * @author zhongminghong
 * @email yunmaozj@qq.com
 * @create 2018-05-25 11:36
 */
public class ClassUtil {

    public static List<Class<?>> getClass(String packName) throws IOException {
        List<Class<?>> classList = new ArrayList<Class<?>>();
        Package pack = Package.getPackage(packName);
        String packageDirName = packName.replaceAll("\\.", "/");
        Enumeration<URL> dirs;
        dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
        while (dirs.hasMoreElements()) {
            URL url = dirs.nextElement();
            String protocol = url.getProtocol();
            if ("file".equals(protocol)) {
                String filepath = URLDecoder.decode(url.getFile(), "UTF-8");
                classList.addAll(FileUtil.getFileClass(packName, filepath));
            } else if ("jar".equals(protocol)) {
                classList.addAll(getJarClass(url,packName));
            }
        }
        for(int i=0;i<classList.size();i++){
            Class clazz = classList.get(i);
            EasyDB easyDB = (EasyDB) clazz.getAnnotation(EasyDB.class);
            if(easyDB == null){
                classList.remove(i);
                i--;
            }

        }
        return classList;
    }

    public static List<Class<?>> getJarClass(URL url, String packageName){
        List<Class<?>> classList = new ArrayList<Class<?>>();
        JarFile jar = null;
        try{
            jar = ((JarURLConnection) url.openConnection()).getJarFile();
        }catch (IOException e){
            e.printStackTrace();
        }
        // 从此jar包 得到一个枚举类
        Enumeration<JarEntry> entries = jar.entries();
        // 同样的进行循环迭代
        while (entries.hasMoreElements()) {
            JarEntry jarEntry = entries.nextElement();
            String name = jarEntry.getName();
            // 如果是以/开头的
            if (name.charAt(0) == '/') {
                // 获取后面的字符串
                name = name.substring(1);
            }
            name = name.replaceAll("/",".");
            if(!jarEntry.isDirectory() && name.endsWith(".class") && name.startsWith(packageName)){
                name =  name.substring(0,name.lastIndexOf(".class"));
                try {
                    Class<?> clazz = Class.forName(name,false,ClassUtil.class.getClassLoader());
                    classList.add(clazz);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (NoClassDefFoundError e){

                }
            }
        }
        return classList;
    }
}
